package com.gamebase.net.rpc
{
	public class RequestCollection
	{	
		private var nextTsn:uint;
		private var first:Request;
		private var last:Request;
		
		public function RequestCollection()
		{
			nextTsn = 1;
			first = null;
			last = null;
		}
		
		public function clearTimeout(interval:uint):void
		{
			var now:Number = (new Date()).getTime();
			var request:Request = last;
			
			while(request!=null)
			{
				if(now-request.sendTime>=interval)
				{
					request.callback.call(null,null);
					
					if(request.next!=null)
					{
						request.next.prev = null;
						first = request.next;
					}
					
					while(request!=null)
					{
						request = request.prev;
						request.next = null;
					}
					
					return;
				}
				
				request = request.prev;
			}
			
		}
		
		public function pushRequest(request:Request):void
		{
			request.tsn = nextTsn;
			nextTsn++;
			
			if(first==null)
			{
				first = request;
			}
			
			if(last==null)
			{
				last = request;
			}
			else
			{
				last.next = request;
				request.prev = last;
				last = request;
			}
			
		}
		
		public function popRequest(tsn:uint):Request
		{
			var request:Request = first;
			
			while(request!=null)
			{
				if(request.tsn==tsn)
				{
					if(request.prev!=null)
					{
						request.prev.next = request.next;
					}
					
					if(request.next!=null)
					{
						request.next.prev = request.prev;
					}
					
					if(first==request)
					{
						first = request.next;
					}
					
					if(last==request)
					{
						last = request.prev;
					}
					
					request.prev = null;
					request.next = null;
					
					return request;
				}
				
				request = request.next;
			}
			
			return request;
		}
	}
}